package com.joe.test_mybatis_plus.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TestTask {
    @Async
    //@Scheduled(cron ="0 0/2 * * * ?")
    public void task(){
        //记录开始时间
        Long start = System.currentTimeMillis();
        System.out.println("开始时间:"+start);
        //定长6线程池
        ExecutorService executor = Executors.newFixedThreadPool(6);
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        for(int i=0;i<6;i++){
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                System.out.println("有返回值的异步任务"+Thread.currentThread().getName());
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 1;
            },executor);
            futures.add(future);
        }
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[futures.size()]));
        CompletableFuture<List<Integer>> finalResults = allFutures.thenApply(v ->
                futures.stream().map(CompletableFuture::join).collect(Collectors.toList())
        );
        List<Integer> resultList =  finalResults.join();
        System.out.println(resultList);
        //记录结束时间
        Long end = System.currentTimeMillis();
        System.out.println("结束时间:"+end);
        Long hao = end - start;
        System.out.println("耗时："+ hao);
    }
}
